/**
 * 
 */

package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.UserBean;

import com.e885.log.E885Logger;

/**
 * url: http://127.0.0.1:8080/AuthenticationFilter/login/login.jsp, 正確的進入點<br>
 * 以下測試是沒有做登入的動作, 都會導回登入頁<br>
 * 1. http://127.0.0.1:8080/AuthenticationFilter/secure/welcome.jsp<br>
 * 2. http://127.0.0.1:8080/AuthenticationFilter/secure/userInfo.jsp<br>
 * 3. http://127.0.0.1:8080/AuthenticationFilter/secure/userInfo<br>
 * <br>
 * 當 login.jsp 按下 OK 鍵之後, 會執行這個 Servlet
 * 
 * @author Eric.Kao(gau168.gau@msa.hinet.net)
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2001-2008
 */

public class LoginServlet extends HttpServlet
{
	private static final long serialVersionUID = -154176561953216931L;

	protected void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
	{
		String id = request.getParameter( "id" );
		String password = request.getParameter( "password" );

		E885Logger.testLog.debug( "id:" + id + ",password:" + password );

		// 驗證帳號密碼的模擬邏輯，實際上是要去資料庫取得
		if( id == null || password == null || !id.equals( "grady" ) || !password.equals( "1234" ) )
		{
			E885Logger.testLog.debug( "account or password is error" );

			request.getRequestDispatcher( "/login/login.jsp" ).forward( request, response );
		}
		else
		{
			HttpSession session = request.getSession( true );

			UserBean bean = new UserBean();
			bean.setId( id );
			bean.setPassword( password );

			session.setAttribute( "UserBean", bean );

			// request.getRequestDispathcer() 的路徑是從 ContextPath 開始算起（也就是有包含 ContextPath ),
			// 如：http://127.0.0.1:8080/AuthenticationFilter/
			// 但是　response.sendRedirect() 就不是了, 如： http://127.0.0.1:8080/
			request.getRequestDispatcher( "/secure/welcome.jsp" ).forward( request, response );
		}
	}
}
